package com.gupao.gupaoeduvippattern.javaBase.a4fanshe.demo02;

import org.junit.jupiter.api.Test;

/**
 *
 * @author Administrator
 * @date 2020-12-22 23:02
 */
public class BallMain {


    /**
     * 反射的缺点：性能低
     */
    @Test
    public void test2(){
        long start = System.currentTimeMillis();
        String key = "Basketball";
        for(int i=1; i<=1000000; i++){
//            getInstanceByObject(key);   // 17ms
            getInstanceByReflect(key);  //1377ms
        }
        long end = System.currentTimeMillis();
        System.out.println("耗时："+(end-start)+"毫秒");

    }


    /**
     * 反射的优点演示：增加程序的灵活性
     * @param args
     */
    public static void main(String[] args) {
        System.out.println(getInstanceByReflect("Basketball"));
    }


    /**
     * 普通代码的写法
     * @param key
     * @return
     */
    public static Ball getInstanceByObject(String key){
        if("Basketball".equals(key)){
            return new Basketball();
        }else if("Football".equals(key)){
            return new Football();
        }

        return null;
    }


    /**
     * 有反射后的用法
     * @param key
     * @return
     */
    public static Ball getInstanceByReflect(String key){
        String basePackage = "com.gupao.gupaoeduvippattern.com.gupao.a4fanshe.demo02";
        Ball ball = null;
        try {
            Class<?> aClass = Class.forName(basePackage +"."+ key);
            ball = (Ball)aClass.newInstance();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }

        return ball;
    }

}
